const express = require('express');
const router = express.Router();
const Class = require('../models/Class');
const Student = require('../models/Student');

/**
 * 获取所有班级列表
 * GET /api/classes
 */
router.get('/', async (req, res) => {
  try {
    const { grade, keyword } = req.query;
    
    // 构建查询条件
    let query = {};
    
    if (grade) {
      query.grade = grade;
    }
    
    if (keyword) {
      query.$or = [
        { className: { $regex: keyword, $options: 'i' } },
        { headTeacher: { $regex: keyword, $options: 'i' } }
      ];
    }
    
    const classes = await Class.find(query).sort({ grade: 1, className: 1 });
    
    // 为每个班级附加学生数量和平均分
    const classesWithStats = await Promise.all(
      classes.map(async (classItem) => {
        const studentCount = await classItem.getStudentCount();
        const averageScore = await classItem.getAverageScore();
        
        return {
          ...classItem.toObject(),
          studentCount,
          averageScore
        };
      })
    );
    
    res.json({
      success: true,
      data: classesWithStats
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '查询失败',
      error: error.message
    });
  }
});

/**
 * 获取年级列表
 * GET /api/classes/filter/grades
 */
router.get('/filter/grades', async (req, res) => {
  try {
    const grades = await Class.distinct('grade');
    
    res.json({
      success: true,
      data: grades.sort()
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '查询失败',
      error: error.message
    });
  }
});

/**
 * 获取单个班级详情
 * GET /api/classes/:id
 */
router.get('/:id', async (req, res) => {
  try {
    const classItem = await Class.findById(req.params.id);
    
    if (!classItem) {
      return res.status(404).json({
        success: false,
        message: '班级不存在'
      });
    }
    
    // 获取班级统计信息
    const studentCount = await classItem.getStudentCount();
    const averageScore = await classItem.getAverageScore();
    
    // 获取班级学生列表
    const students = await Student.find({ class: classItem.className });
    
    res.json({
      success: true,
      data: {
        ...classItem.toObject(),
        studentCount,
        averageScore,
        students
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '查询失败',
      error: error.message
    });
  }
});

/**
 * 创建新班级
 * POST /api/classes
 */
router.post('/', async (req, res) => {
  try {
    const { className, grade, headTeacher, description } = req.body;
    
    // 检查班级名称是否已存在
    const existingClass = await Class.findOne({ className });
    if (existingClass) {
      return res.status(400).json({
        success: false,
        message: '班级名称已存在'
      });
    }
    
    const newClass = new Class({
      className,
      grade,
      headTeacher,
      description
    });
    
    await newClass.save();
    
    res.status(201).json({
      success: true,
      message: '创建成功',
      data: newClass
    });
  } catch (error) {
    if (error.name === 'ValidationError') {
      return res.status(400).json({
        success: false,
        message: '数据验证失败',
        error: error.message
      });
    }
    
    res.status(500).json({
      success: false,
      message: '创建失败',
      error: error.message
    });
  }
});

/**
 * 更新班级信息
 * PUT /api/classes/:id
 */
router.put('/:id', async (req, res) => {
  try {
    const { className, grade, headTeacher, description } = req.body;
    
    const classItem = await Class.findById(req.params.id);
    
    if (!classItem) {
      return res.status(404).json({
        success: false,
        message: '班级不存在'
      });
    }
    
    // 如果修改了班级名称，检查新名称是否已存在
    if (className && className !== classItem.className) {
      const existingClass = await Class.findOne({ className });
      if (existingClass) {
        return res.status(400).json({
          success: false,
          message: '班级名称已存在'
        });
      }
      
      // 更新所有学生的班级信息
      await Student.updateMany(
        { class: classItem.className },
        { class: className }
      );
    }
    
    // 更新班级信息
    if (className) classItem.className = className;
    if (grade) classItem.grade = grade;
    if (headTeacher !== undefined) classItem.headTeacher = headTeacher;
    if (description !== undefined) classItem.description = description;
    
    await classItem.save();
    
    res.json({
      success: true,
      message: '更新成功',
      data: classItem
    });
  } catch (error) {
    if (error.name === 'ValidationError') {
      return res.status(400).json({
        success: false,
        message: '数据验证失败',
        error: error.message
      });
    }
    
    res.status(500).json({
      success: false,
      message: '更新失败',
      error: error.message
    });
  }
});

/**
 * 删除班级
 * DELETE /api/classes/:id
 */
router.delete('/:id', async (req, res) => {
  try {
    const classItem = await Class.findById(req.params.id);
    
    if (!classItem) {
      return res.status(404).json({
        success: false,
        message: '班级不存在'
      });
    }
    
    // 检查是否有学生
    const studentCount = await Student.countDocuments({ class: classItem.className });
    if (studentCount > 0) {
      return res.status(400).json({
        success: false,
        message: `该班级下还有${studentCount}名学生，无法删除`
      });
    }
    
    await classItem.deleteOne();
    
    res.json({
      success: true,
      message: '删除成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '删除失败',
      error: error.message
    });
  }
});

/**
 * 同步学生表中的班级数据到班级管理表
 * POST /api/classes/sync
 */
router.post('/sync', async (req, res) => {
  try {
    // 获取学生表中所有唯一的班级名称
    const classNames = await Student.distinct('class');
    
    if (!classNames || classNames.length === 0) {
      return res.json({
        success: true,
        message: '没有需要同步的班级数据',
        data: {
          synced: 0,
          skipped: 0,
          total: 0
        }
      });
    }
    
    let syncedCount = 0;
    let skippedCount = 0;
    
    // 遍历每个班级名称
    for (const className of classNames) {
      if (!className || className.trim() === '') {
        skippedCount++;
        continue;
      }
      
      // 检查班级是否已存在
      const existingClass = await Class.findOne({ className });
      
      if (existingClass) {
        skippedCount++;
        continue;
      }
      
      // 尝试从班级名称中提取年级信息
      // 例如："2023级1班" -> "2023级"
      let grade = '';
      const gradeMatch = className.match(/(\d{4}级|[一二三四五六]年级|高[一二三]|初[一二三])/);
      if (gradeMatch) {
        grade = gradeMatch[1];
      } else {
        // 如果无法提取，使用默认值
        grade = '未分类';
      }
      
      // 创建新的班级记录
      const newClass = new Class({
        className,
        grade,
        description: '自动同步创建'
      });
      
      await newClass.save();
      syncedCount++;
    }
    
    res.json({
      success: true,
      message: `同步完成，新增 ${syncedCount} 个班级，跳过 ${skippedCount} 个已存在的班级`,
      data: {
        synced: syncedCount,
        skipped: skippedCount,
        total: classNames.length
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '同步失败',
      error: error.message
    });
  }
});

/**
 * 获取班级统计信息
 * GET /api/classes/:id/statistics
 */
router.get('/:id/statistics', async (req, res) => {
  try {
    const classItem = await Class.findById(req.params.id);
    
    if (!classItem) {
      return res.status(404).json({
        success: false,
        message: '班级不存在'
      });
    }
    
    const students = await Student.find({ class: classItem.className });
    
    // 统计各课程成绩
    const courseStats = {};
    
    students.forEach(student => {
      if (student.scores && student.scores.length > 0) {
        student.scores.forEach(scoreItem => {
          if (!courseStats[scoreItem.courseName]) {
            courseStats[scoreItem.courseName] = {
              courseName: scoreItem.courseName,
              scores: [],
              count: 0,
              total: 0,
              average: 0,
              max: 0,
              min: 100
            };
          }
          
          const stat = courseStats[scoreItem.courseName];
          stat.scores.push(scoreItem.score);
          stat.count++;
          stat.total += scoreItem.score;
          stat.max = Math.max(stat.max, scoreItem.score);
          stat.min = Math.min(stat.min, scoreItem.score);
        });
      }
    });
    
    // 计算平均分
    Object.values(courseStats).forEach(stat => {
      stat.average = (stat.total / stat.count).toFixed(2);
      delete stat.scores; // 不返回原始分数数组
    });
    
    res.json({
      success: true,
      data: {
        className: classItem.className,
        studentCount: students.length,
        courseStats: Object.values(courseStats)
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '查询失败',
      error: error.message
    });
  }
});

module.exports = router;
